var crypto = require('../utils/crypto');
var db = require('./db');

var io = null;
exports.start = function(config,mgr){
    io = require('socket.io')(config.GAME_PORT);
	io.sockets.on('connection',function(socket){
		socket.on('login',function(data){
            data = JSON.parse(data);
			if(socket.userId != null){
				//已经登陆过的就忽略
				return;
			}
			var userId = data.id;
			var salt = data.salt;
			var username = data.username;
			//检查参数合法性
			if(userId == null || salt == null){
				socket.emit('login_finished',{code:-1,msg:"登录参数错误"});
				return;
			}
			db.is_user_exist(username,salt,(res)=>{
				if (!res){
					socket.emit('login_finished',{code:-1,msg:"登录参数错误"});
					return;
				}

				







				socket.userId = userId;
				socket.emit('login_finished',{code:1,msg:'登录成功'});
			});

        });
        
		
		//断开链接
		socket.on('disconnect',function(data){
			var userId = socket.userId;
			console.log('userId==>',userId);
			if(!userId){
				return;
			}
			// var data = {
			// 	userid:userId,
			// 	online:false
			// };

			// //通知房间内其它玩家
			// userMgr.broacastInRoom('user_state_push',data,userId);

			// //清除玩家的在线信息
			// userMgr.del(userId);
			// socket.userId = null;
		});

        // 心跳
		socket.on('game_ping',function(data){
			var userId = socket.userId;
			if(!userId){
				return;
			}
			console.log('game_ping');
			socket.emit('game_pong');
		});
        
    });
    
	console.log('\x1B[32m',"ddz game socket-server is listening on " + config.GAME_IP + ":"  + config.GAME_PORT);	
};
